#encoding='utf-8'
import os
import sys
import shutil
import time
import subprocess
import json
import collections
from .telink_bin_make import OTA_bin_build

#*****************************************************************#
# NOTE: This script is a compiled script. Please do not modify it #
#*****************************************************************#
# Post Build processing.

# source tuyaos_zigbee_light_sample tc32 1.0.0

# SOURCE_PTAH = sys.argv[1]
# SOURCE_NAME = os.path.basename(SOURCE_PTAH)
# APP_NAME = sys.argv[2]
# MODE = sys.argv[3]
# PROJECT_VERSION = sys.argv[4]

APP_PATH = sys.argv[1]

CURR_PATH = os.getcwd()
CURR_PATH = CURR_PATH.replace("\\", "/")

APP_PROJ_PATH = ''
JSON_CONFIG_NAME = 'appconfig.json'
JSON_CONFIG_PATH = os.path.join(APP_PROJ_PATH, JSON_CONFIG_NAME)

def deldir(dir):
    if not os.path.exists(dir):
        return False
    if os.path.isfile(dir):
        os.remove(dir)
        return
    for i in os.listdir(dir):
        t = os.path.join(dir, i)
        if os.path.isdir(t):
            deldir(t)#重新调用次方法
        else:
            os.unlink(t)
    os.rmdir(dir)#递归删除目录下面的空文件夹


# version info convert
def version_string_to_hex(version):
    str = version.replace('.', '')
    strlen = len(str)
    version_hex = ((int(str[0:1]) << 6) & 0xc0) + ((int(str[1:2]) << 4) & 0x30)
    if (strlen > 3):
        version_hex = version_hex + (int(str[2:4]) & 0x0f)
    else:
        version_hex = version_hex + (int(str[2:3]) & 0x0f)
    # print(hex(version_hex))
    return version_hex

# print("*****************************************************") 
# print("this is post build!! current configure is :"+APP_NAME)


# firmware info parser
def firmware_info_get():
    global MANUFACTURE_ID
    global IMAGE_TYPE
    file = open(JSON_CONFIG_PATH, 'rb')
    fileJson = json.load(file, object_pairs_hook=collections.OrderedDict)

    MANUFACTURE_ID = fileJson['firmwareInfo']['manufacture_id']
    IMAGE_TYPE = fileJson['firmwareInfo']['image_type']

    file.close()

# if  MODE == 'tc32' :

class OTA_build(object):
    def __init__(self,SOURCE_NAME,APP_NAME,MODE,PROJECT_VERSION):
        global CURR_PATH
        CURR_PATH = CURR_PATH+'/'+SOURCE_NAME+'/_build'

        os.chdir(CURR_PATH)
        os.chdir('../../../tools/tc32/tc32/bin/')
        os.system('tc32-elf-objcopy -v -O binary' + ' '+CURR_PATH+'/'+APP_NAME+'.elf'+' '+CURR_PATH+'/'+APP_NAME+'.bin')
        os.chdir(CURR_PATH)

        os.chdir('../../../tools/OTA/')
        os.system('tl_check_fw2' + ' '+CURR_PATH+'/'+APP_NAME+'.bin')
        os.chdir(CURR_PATH)

        deldir('../../../tools/OTA/'+APP_NAME+'.bin')
        shutil.copyfile(APP_NAME+'.bin','../../../tools/OTA/'+APP_NAME+'.bin')
        deldir(APP_NAME+'.bin')

        os.chdir('../../../tools/OTA/')

        OTA_bin_build('telink_8258_bootloader.bin',32,APP_NAME+'.bin')
            
        deldir('zbGitVersionCode.bin')
        os.rename(APP_NAME+'.bin','zbGitVersionCode.bin')
        version_hex = hex(version_string_to_hex(PROJECT_VERSION))
        version_hex = version_hex.replace('0x','00')
        print('0000'+str(version_hex)+'\n')

        os.chdir('../../'+APP_PATH)
        firmware_info_get()
        os.chdir('../../tools/OTA/')

        dev=subprocess.Popen("tl_ota_tool_1.0.exe",stdin=subprocess.PIPE,stdout=subprocess.PIPE,env=None,universal_newlines=True,bufsize=1)
        dev.stdin.write(MANUFACTURE_ID+'\n')       # Manufaurer Code
        dev.stdin.write(IMAGE_TYPE+'\n')    	# OTA Image Type
        dev.stdin.write('0000'+str(version_hex)+'\n')   # OTA File version
        dev.communicate()

        shutil.copyfile('pack_file.bin','../../apps/'+APP_NAME +'/output/'+APP_NAME+'_QIO_'+PROJECT_VERSION+'.bin')
        shutil.copyfile('ota.ota','../../apps/'+APP_NAME +'/output/'+APP_NAME+'_UG_'+PROJECT_VERSION+'.bin')
        
        deldir(APP_NAME+'.bin')  
        deldir('pack_file.bin')
        deldir('ota.ota')
        deldir('zbGitVersionCode.bin')
        
        os.chdir(CURR_PATH)

        os.chdir('../../../tools/tc32/tc32/bin/')
        print('Invoking: TC32 Create Extended Listing')
        print('tc32-elf-objdump -x -D -l -S' + ' '+APP_NAME+'.elf'+' '+'>'+'boot-.lst')
        os.system('tc32-elf-objdump -x -D -l -S' + ' '+CURR_PATH+'/'+APP_NAME+'.elf'+' '+'>'+CURR_PATH+'/boot-.lst')
        print('Finished building: boot-.lst')
        print('\n')
        os.chdir(CURR_PATH)

print("**************** end of post build ******************")
